package com.heima.comment.service.impl;

import com.heima.apis.ap_user.IApUserClient;
import com.heima.apis.sensitive.ISensitiveClient;
import com.heima.comment.ParamCheckUtil;
import com.heima.comment.aliyun.GreenTextScan;
import com.heima.comment.service.CommentService;
import com.heima.comment.service.CommentUserService;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentSaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.CommentUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.CommentUserThreadLocalUtil;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * @author jay
 * @date 2022/11/16 14:34:55
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IApUserClient apUserClient;

    @Autowired
    private ISensitiveClient sensitiveClient;

    @Autowired
    private CommentUserService commentUserService;

    @Autowired
    private GreenTextScan greenTextScan;

    @Override
    public ResponseResult save(CommentSaveDto dto) {
        // 1.参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 1.1 检查用户是否存在, 检查评论是否违规
        ApComment comment = ParamCheckUtil.isCheckPasted(dto.getContent(), dto.getArticleId(), apUserClient, sensitiveClient, greenTextScan);
        if (comment == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.COMMENT_CONTAINS_SENSITIVE);
        }

        // 2. 数据准备
        comment.setType((short) 0);

        // 3.保存评论
        mongoTemplate.save(comment);

        // 4.返回结果
        return ResponseResult.okResult("评论成功");
    }

    @Override
    public ResponseResult load(CommentDto dto) {
        // 1.参数校验
        if (!(dto != null && dto.getArticleId() != null
                && dto.getIndex() != null && dto.getIndex() > 0
                && dto.getMinDate() != null && dto.getMinDate() > 0)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2.查询
        List<ApComment> comments = null;
        Query query = new Query();
        query.addCriteria(Criteria.where("entryId").is(dto.getArticleId()));
        query.addCriteria(Criteria.where("type").is(0));
        query.addCriteria(Criteria.where("createdTime").lte(dto.getMinDate()));
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        if (dto.getIndex() > 1) {
            query.skip(dto.getIndex());
        }
        query.limit(20);
        comments = mongoTemplate.find(query, ApComment.class);
        comments.forEach(itm -> {
            itm.setOperation(commentUserService.isStared(itm.getId()) ? 0 : 1);
        });
        // 3.返回结果
        return ResponseResult.okResult(comments);
    }

    @Override
    public ResponseResult like(CommentLikeDto dto) {
        // 1.参数检测
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 校验指定评论是否存在

        ApComment apComment = mongoTemplate.findById(new ObjectId(dto.getCommentId()), ApComment.class);
        if (apComment == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 2.更新
        HashMap<String, Integer> resultMap = new HashMap<>();
        Update update = new Update();
        if (dto.getOperation() == 0) {
            update.set("likes", apComment.getLikes() + 1);
            resultMap.put("likes", apComment.getLikes() + 1);
            commentUserService.save(dto.getCommentId());
        } else if (dto.getOperation() == 1 && apComment.getLikes() > 0) {
            // likes必须大于0才能减少
            update.set("likes", apComment.getLikes() - 1);
            resultMap.put("likes", apComment.getLikes() - 1);
            commentUserService.delete(dto.getCommentId());
        }
        Query query = Query.query(Criteria.where("_id").is(new ObjectId(dto.getCommentId())));
        mongoTemplate.updateFirst(query, update, ApComment.class);

        // 3.返回结果
        return ResponseResult.okResult(resultMap);
    }
}
